package com.android.museum.view

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.FrameLayout
import com.android.museum.R
import kotlin.math.abs

class ProductDisplayView @JvmOverloads constructor(
    context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0
) : FrameLayout(context, attributeSet, defStyle) {
    private val mSlop = resources.getDimension(R.dimen.product_display_slop)
    private var mDownX: Float = 0f
    private var mDownY: Float = 0f
    private var mHandled: Boolean = false

    init {
        LayoutInflater.from(context).inflate(R.layout.product_display_view, this)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return event?.let {
            when (it.action and MotionEvent.ACTION_MASK) {
                MotionEvent.ACTION_DOWN -> {
                    mHandled = false
                    mDownX = it.x
                    mDownY = it.y
                    return true
                }

                MotionEvent.ACTION_MOVE -> {
                    val moveX = it.x - mDownX
                    val moveY = it.y - mDownY

                    if (abs(moveY) > abs(moveX) && abs(moveY) >= mSlop && !mHandled) {
                        mHandled = true
                        if (moveY > 0) {
                            (parent.parent as MuseumContentView).showDisplayView()
                        } else {
                            (parent.parent as MuseumContentView).showDescriptionView()
                        }
                        return true
                    }
                    return false
                }

                else -> {
                    return false
                }
            }
        } ?: false
    }
}